var express = require('express');
var router = express.Router();
var fs = require('fs');
var path = require('path');


/* GET users listing. */

//   /musics
router.get('/', function(req, res, next) {

    var data = fs.readFileSync(path.join(__dirname,'..','config','music.json'));

    var obj = JSON.parse(data.toString());

    res.json({
		code: 0,
		dat: obj
	});
});

router.get('/toPlay',function (req, res) {

    return res.redirect('/views/musicPlay.html');
});

// define a route music it creates readstream to the requested file and pipes the output to response

router.get('/play', function(req,res){
	
	var fileId = req.query.id; 
	var file = path.join(__dirname , '../','music' , fileId);
	fs.exists(file,function(exists){
		if(exists)
		{
			var rstream = fs.createReadStream(file);
			rstream.pipe(res);
		}
		else
		{
			res.send("Its a 404");
			res.end();
		}
	
	});
});



// following is the code for downloading music files, note that the code remains same except that we add 2 headers viz
// Content-disposition and Content-Type which forces the chrome browser to force download rather than playing the media
// Note that the following is tested with google chrome and it may work differently in Mozilla and Opera based on your 
// installed plugins.

router.get('/download', function(req,res){
	var fileId = req.query.id;
	var file = path.join(__dirname , '../','music' , fileId);
	fs.exists(file,function(exists){
		if(exists)
		{
			res.setHeader('Content-disposition', 'attachment; filename=' + fileId);
			res.setHeader('Content-Type', 'application/audio/mpeg3')
			var rstream = fs.createReadStream(file);
			rstream.pipe(res);
		}
		else
		{
			res.send("Its a 404");
			res.end();
		}
	});
});

module.exports = router;
